<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    v-bind="$attrs"
    @open="handlerOpen"
    v-on="$listeners"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="用户名称" prop="username">
        <el-input v-model="form.username" :disabled="this.type !== 1" />
      </el-form-item>
      <template v-if="type === 1">
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmpwd">
          <el-input v-model="form.confirmpwd" type="password" />
        </el-form-item>
      </template>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="form.mobile" />
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="resetForm('form')">重置</el-button>
      <el-button type="primary" @click="handlerForm('form')">提交</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { postUser, getUserInfo, putUser } from '@/api/user'

function rules(_this) {
  return {
    username: [
      { required: true, message: '请输入用户名称', trigger: 'blur' },
      { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入用户密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
    ],
    confirmpwd: [
      { required: true, message: '请输入确认密码', trigger: 'blur' },
      { validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入确认密码'))
        } else if (value !== _this.form.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
      }
    ],
    email: [
      { validator: (rule, value, callback) => {
        const pattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
        if (value === '') {
          callback()
        } else if (!pattern.test(value)) {
          callback('请输入正确的邮箱')
        } else {
          callback()
        }
      },
      trigger: 'blur'
      }
    ],
    mobile: [
      { validator: (rule, value, callback) => {
        const pattern = /^1[3456789]\d{9}$/
        if (value === '') {
          callback()
        } else if (!pattern.test(value)) {
          callback('请输入正确的手机号码')
        } else {
          callback()
        }
      },
      trigger: 'blur'
      }
    ]
  }
}

export default {
  name: 'USERFORM',
  props: {
    type: {
      type: Number,
      default: 3
    },
    id: {
      type: [Number, String]
    },
    cb: {
      type: Function
    }
  },
  data() {
    return {
      form: {
        username: '',
        password: '',
        confirmpwd: '',
        email: '',
        mobile: ''
      },
      rules: rules(this)
    }
  },
  computed: {
    title() {
      let str = ''
      if (this.type === 1) {
        str = '添加'
      } else if (this.type === 2) {
        str = '编辑'
      } else {
        str = '查看'
      }
      return str + '用户'
    }
  },
  methods: {
    handlerOpen() {
      this.resetForm('form')
      if (this.type !== 1) {
        this.getUserInfo()
      }
    },
    resetForm(formName) {
      this.$refs[formName] && this.$refs[formName].resetFields()
    },
    handlerForm(formName) {
      if (this.type === 1) {
        this.submitForm(formName)
      } else if (this.type === 2) {
        this.updateUser(formName)
      } else {
        return false
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          await postUser(this.form)
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.$emit('update:visible', false)
          this.cb && this.cb()
        } else {
          return false
        }
      })
    },
    updateUser(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          const data = {
            id: this.form.id,
            email: this.form.email,
            mobile: this.form.mobile
          }
          await putUser(data)
          this.$message({
            message: '编辑成功',
            type: 'success'
          })
          this.$emit('update:visible', false)
          this.cb && this.cb()
        } else {
          return false
        }
      })
    },
    async getUserInfo() {
      const data = await getUserInfo(this.id)
      console.log('data:::', data)
      this.form = { ...this.form, ...data }
      console.log('this.form::', this.form)
    }
  }
}
</script>
